<?php

namespace App\Http\Controllers\CharterBus;

use App\Http\Controllers\Controller;
use App\Http\Controllers\HelperController;
use App\Imports\CharterBus\CharterBusImport;
use App\Models\CharterBus\CharterBus;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Facades\Excel;

class CharterBusController extends Controller
{
    /**
     * 包车明细列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function charterBusList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);

        $data = $this->getCharterBusList($params)->orderByDesc('date_time')->get()->toArray();
        $dataCount = $this->getCharterBusList($countParams)->count();

        return response()->formatJson(['personnel' => $data, 'count' => $dataCount]);
    }

    public function getCharterBusList($params)
    {
        $query = CharterBus::query();

        if (isset($params['license_plate_num'])) {
            $query
                ->where('license_plate_num', 'like', '%'.$params['license_plate_num'].'%');
        }

        if ($params['date_time'][0] !== null && $params['date_time'][1] !== null) {
            $startDate = date('Y-m-d', strtotime($params['date_time'][0]));
            $endDate = date('Y-m-d', strtotime($params['date_time'][1]));
            $query->whereBetween('date_time', [$startDate, $endDate]);
        }

        if (isset($params['pageNumber'], $params['pageSize'])) {
            $query
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }

        return $query;
    }

    /**
     * 获取包车明细详情
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function charterBusInfo(Request $request)
    {
        $params = $request->all();
        $data = DB::table('akbus_charter_bus')
            ->where('id', $params['id'])
            ->first();
        return response()->formatJson(['result' => $data]);
    }

    /**
     * 添加包车明细
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function addCharterBus(Request $request)
    {
        $params = $request->all();
        $params['created_at'] = date('Y-m-d H:i:s');
        unset($params['id']);
        $data = CharterBus::query()->insertGetId($params);
        $result = $data ? true : false;
        return response()->formatJson(['result' => $result]);
    }

    /**
     * 编辑包车明细
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function editCharterBus(Request $request)
    {
        $params = $request->all();
        $id = $params['id'];
        $params['updated_at'] = date('Y-m-d H:i:s');
        unset($params['id']);
        $data = CharterBus::query()->where('id', $id)->update($params);
        $result = $data ? true : false;
        return response()->formatJson(['result' => $result]);
    }

    /**
     * 删除包车明细
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function delCharterBus(Request $request)
    {
        $result = false;
        if ($request->has('ids')) {
            $ids = explode(',', $request['ids']);
            $delCount = CharterBus::destroy($ids);
            $result = $delCount !== 0;
        }

        $message = $result ? '删除成功' : '删除失败';

        return response()->formatJson($result, $message);
    }

    /**
     * 导入包车收入
     *
     * @param  Request  $request
     *
     * @return mixed
     * @throws \Exception
     */
    public function importCharterBus(Request $request)
    {
        $urlParse = parse_url($request->input('url'));
        $excelData = Excel::toArray(new CharterBusImport, public_path().$urlParse['path']);
        $fullData = $excelData[0];

        array_shift($fullData);

        $data = [];
        $fields = [
            'id',
            'date_time',
            'license_plate_num',
            'start_bus_time',
        ];
        // 整理数据，填充合并的单元格数据
        foreach ($fullData as $k => $row) {
            $item = [];
            if ($k > 0) {
                foreach ($fields as $index => $field) {
                    $item[$field] = $row[$index];
                }
                if ($item['license_plate_num']) {
                    $item['license_plate_num'] = Str::of($item['license_plate_num'])->replace('陕G', '');
                }
                $item['date_time'] = HelperController::transformDateTime($item['date_time']);
                $item['created_at'] = date('Y-m-d H:i:s');
                unset($item['id']);
                $data[] = $item;
            }
        }
        foreach ($data as $k => $item) {
            $result = CharterBus::query()->updateOrCreate(
                [
                    'license_plate_num' => $item['license_plate_num'],
                    'date_time'         => $item['date_time'],
                    'start_bus_time'    => $item['start_bus_time'],
                ], $item
            );
        }

        $message = $result ? '导入成功' : '导入失败';

        return response()->formatJson($result, $message);
    }
}
